#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.domain.AlipayTradeCreateModel import AlipayTradeCreateModel
from alipay.aop.api.request.AlipayTradeCreateRequest import AlipayTradeCreateRequest
#修改请求方法
from alipay.aop.api.request.AlipayTradePrecreateRequest import AlipayTradePrecreateRequest
from alipay.aop.api.response.AlipayTradeCreateResponse import AlipayTradeCreateResponse
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s',
    filemode='a',)

def get_key(path):
    '''获取公钥私钥'''
    s = None
    with open(path,'r') as f:
        s = f.read()
    return s
 # 实例化客户端
logger = logging.getLogger('')
alipay_client_config = AlipayClientConfig()
'''https://openapi.alipay.com/gateway.do?timestamp=2013-01-01 08:08:08&
#method=alipay.trade.precreate&app_id=24604&sign_type=RSA2&sign=ERITJKEIJKJHKKKKKKKHJEREEEEEEEEEEE&
version=1.0&charset=GBK&biz_content=AlipayTradePrecreateModel
'''
# alipay_client_config.server_url = 'https://openapi.alipaydev.com/gateway.do'
#更改为沙箱环境网关
alipay_client_config.server_url = 'https://openapi-sandbox.dl.alipaydev.com/gateway.do'
alipay_client_config.app_id = '9021000125668620'
alipay_client_config.app_private_key = get_key('./keys/app_private_key.pem')
alipay_client_config.alipay_public_key = get_key('./keys/ali_public_key.pem')
client = DefaultAlipayClient(alipay_client_config, logger)

def get_req(out_trade_no,total_amount,subject):
 # 构造请求参数对象
    model = AlipayTradeCreateModel()
    model.out_trade_no = out_trade_no
    model.total_amount = total_amount
    model.subject = subject
    # model.buyer_id = "2088******846880"   可选参数
    #更改请求模块（原来：AlipayTradeCreateRequest）
    request = AlipayTradePrecreateRequest(biz_model=model)
    # 执行API调用
    response_content = False
    try:
        response_content = client.execute(request)
    except Exception as e:
        import traceback
        print(traceback.format_exc())
    return response_content
    # if not response_content:
    #     print("failed execute")
    # else:
    #     # 解析响应结果
    #     response = AlipayTradeCreateResponse()
    #     response.parse_response_content(response_content)
    #     # 响应成功的业务处理
    #     if response.is_success():
    #         # 如果业务成功，可以通过response属性获取需要的值
    #         print("get response trade_no:" + str(response.trade_no))
    #     # 响应失败的业务处理
    #     else:
    #         # 如果业务失败，可以从错误码中可以得知错误情况，具体错误码信息可以查看接口文档
    #         print(response.code + "," + response.msg + "," + response.sub_code + "," + response.sub_msg)
if __name__ == '__main__':
   print(get_req("20150320010101001","88.88","Iphone6 16G"))
   